import axios from 'axios';
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
import { Message, Modal } from '@arco-design/web-vue';
import { useUserStore } from '@/store';
import { getToken } from '@/utils/auth';

export interface HttpResponse<T = unknown> {
	message : string;
	code : number;
	data : T;
}

if (import.meta.env.VITE_API_BASE_URL) {
	axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL;
}

axios.interceptors.request.use(
	(config : AxiosRequestConfig) => {
		// let each request carry token
		// this example using the JWT token
		// Authorization is a custom headers key
		// please modify it according to the actual situation
		const token = getToken();
		if (token) {
			if (!config.headers) {
				config.headers = {};
			}
			config.headers.Authorization = `Bearer ${token}`;
		}
		console.log("request=>请求", config.baseURL, config.url,"params:", config.params,"data:",config.data)
		return config;
	},
	(error) => {
		// do something
		return Promise.reject(error);
	}

);
// add response interceptors
axios.interceptors.response.use(
	(response : AxiosResponse<HttpResponse>) => {
		console.log("响应", response.data)
		const res = response.data;
		// if the custom code is not 20000, it is judged as an error.
		if (![200, 20000].includes(res.code)) {
			Message.error({
				content: res.message || '网络连接有问题',
				duration: 5 * 1000,
			});
			// 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
			if (
				[406, 401, 403].includes(res.code) &&
				response.config.url !== '/auth/oauth/token'
			) {
				Modal.error({
					title: '注意',
					content:
						'请重新登录',
					okText: '',
					async onOk() {
						const userStore = useUserStore();
						await userStore.logout();
						window.location.reload();
					},
				});
			}
			return Promise.reject(new Error(res.message || '网络连接有问题'));
		}
		return res;
	},
	(error) => {
		Message.error({
			content: error.message || 'Request Error',
			duration: 5 * 1000,
		});
		return Promise.reject(error);
	}
);